home *** CD-ROM | disk | FTP | other *** search
/ NetNews Offline 2 / NetNews Offline Volume 2.iso / news / comp / std / c / 245 < prev    next >
Text File  |  1996-08-06  |  2KB  |  77 lines

  1. Path: mail2news.demon.co.uk!hpl3sn03.cern.ch
  2. From: Dan Pop <danpop@mail.cern.ch>
  3. Newsgroups: comp.std.c
  4. Subject: Re: Two questions - Pointer equality and ...
  5. Date: Wed, 31 Jan 1996 02:55:01 +0100
  6. Organization: CERN European Lab for Particle Physics
  7. Message-ID: <9601310155.AA07417@dxmint.cern.ch>
  8. References: <4elq8a$j0b@taurus.fccc.edu> <TANMOY.96Jan30150808@qcd.lanl.gov>
  9. X-NNTP-Posting-Host: hpl3sn03.cern.ch
  10. X-Newsreader: NN version 6.5.0 #7 (NOV)
  11. X-Mail2News-Path: dxmint.cern.ch!hpl3sn03.cern.ch
  12.  
  13. tanmoy@qcd.lanl.gov (Tanmoy Bhattacharya) writes:
  14.  
  15. >In article <4elq8a$j0b@taurus.fccc.edu> slifker@castor.fccc.edu
  16. >(Michael J. Slifker) writes: 
  17. >
  18. >   I've compiled the following program with gcc:
  19. >
  20. >   -----------
  21. >
  22. >   #include <stdio.h>
  23. >
  24. >   char *str1 = "Hello, World\n";
  25. >   const char *str2 = "Hello, World\n";
  26. >
  27. >   int main(void)
  28. >   {
  29. >     str1[0] = 'J';
  30. >     printf("%s", str2);
  31. >     return 0;
  32. >   }
  33. >
  34. >   -----------
  35. >
  36. >   ...and it prints out "Jello, World". This seems odd, at least to
  37. >   me. Is this a bug, or is the behavior above officially undefined?
  38. >
  39. >Attempt to modify a string literal results in undefined behaviout. Any
  40. >behaviour by the implementation is then valid.
  41.  
  42. The full answer is in ANSI classic 3.1.4:
  43.  
  44.     Identical string literals of either form need not be distinct.  If
  45.     the program attempts to modify a string literal of either form, the
  46.     behavior is undefined.
  47.  
  48. So, if we modify main() in the above example to look like this:
  49.  
  50.     int main(void)
  51.     {
  52.        printf("%d\n", str1 == str2);
  53.        return 0;
  54.     }
  55.  
  56. Both "0" and "1" are correct outputs.  Different compilers on the same
  57. platform may produce diferent results:
  58.  
  59.     ues5:~/tmp 88> gcc test.c
  60.     ues5:~/tmp 89> ./a.out 
  61.     1
  62.     ues5:~/tmp 90> cc test.c
  63.     ues5:~/tmp 91> ./a.out
  64.     0
  65.  
  66. This actually explains the (undefined) behaviour observed by the original
  67. poster.  There are systems where the attempt to modify a string literal
  68. results in a segmentation fault, because string literals are put in a 
  69. read-only memory segment.
  70.  
  71. Dan
  72. -- 
  73. Dan Pop
  74. CERN, CN Division
  75. Email: danpop@mail.cern.ch 
  76. Mail:  CERN - PPE, Bat. 31 R-004, CH-1211 Geneve 23, Switzerland
  77.